package com.peas.platform.common.core.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @author caizhh
 */
public class MultipartFileUtil {

    @SneakyThrows
    public static void initDownloadHeader(HttpServletRequest request, HttpServletResponse response, String mediaType, String filename) {
        assert request != null;
        String name = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment; filename=\"" + name + "\"");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        if (StrUtil.isBlank(mediaType) || StrUtil.equalsIgnoreCase("application", mediaType)) {
            mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        response.setContentType(mediaType + ";charset=utf-8");
    }

    public static void initDownloadHeader(HttpServletRequest request, HttpServletResponse response, MediaType mediaType, String filename) {
        initDownloadHeader(request, response, mediaType.getType(), filename);
    }

    public static void initDownloadHeader(HttpServletRequest request, HttpServletResponse response, String filename) {
        initDownloadHeader(request, response, MediaType.APPLICATION_OCTET_STREAM, filename);
    }

    @SneakyThrows
    public static MultipartFile fileToCommonsMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());
        try (InputStream input = Files.newInputStream(file.toPath());
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IoUtil.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * XWPFDocument 转 MultipartFile（CommonsMultipartFile）
     *
     * @param document 文档对象
     * @param fileName 文件名
     * @return MultipartFile
     */
    @SneakyThrows
    public static MultipartFile xwpfDocumentToCommonsMultipartFile(XWPFDocument document, String fileName) {
        //XWPFDocument转FileItem
        FileItemFactory factory = new DiskFileItemFactory(10240, null);
        FileItem fileItem = factory.createItem("textField", "text/plain", true, fileName);
        OutputStream os = fileItem.getOutputStream();
        document.write(os);
        os.close();
        return new CommonsMultipartFile(fileItem);
    }

    /**
     * Workbook 转 MultipartFile(CommonsMultipartFile)
     *
     * @param workbook excel文档
     * @param fileName 文件名
     * @return MultipartFile
     */
    @SneakyThrows
    public static MultipartFile workbookToCommonsMultipartFile(Workbook workbook, String fileName) {
        //Workbook转FileItem
        FileItemFactory factory = new DiskFileItemFactory(10240, null);
        FileItem fileItem = factory.createItem("textField", "text/plain", true, fileName);
        OutputStream os = fileItem.getOutputStream();
        workbook.write(os);
        os.close();
        return new CommonsMultipartFile(fileItem);
    }

}
